#!/usr/bin/groovy

/*
Build docker image and push to private registry
Example call: 

def name = 'mobtech.com'
def img_subpath = 'dev'
def project_repo_url = "https://github.com/mobtech/${name}.git"
def githubAuth = 'mobgithubauth'
def node_label = 'docker-build'
def registry='registry.mobtech.com:8080'
def registryAuth='mobregistryauth'
buildImage name: name, img_subpath:img_subpath, 
            project_repo_url:project_repo_url,
            githubAuth:githubAuth, 
            node_label:node_label,
            registry:registry
            registryAuth:registryAuth
 
*/
def call(Map config){
    def ppl = new com.mobtech.ci.Pipeline()
    //node("${config.node_label}") {
        stage("Check out ${config.name} latest code") {
            checkout changelog: false, poll: false,
                    scm: [$class: 'GitSCM', branches: scm.branches,
                          extensions: [[$class: 'CloneOption', noTags: true, reference: '', shallow: true]],
                          userRemoteConfigs: [[credentialsId: config.githubAuth, url: config.project_repo_url]]]
            // set additional git envvars for image tagging
            ppl.gitEnvVars()
        }
        def now= new Date().format("yyMMdd_HHmm", TimeZone.getTimeZone('UTC'))
        def tag = "${now}-${env.GIT_SHA}"
        def buildArgs = [BUILD_VERSION:tag]
        if (config.args) {
            buildArgs.putAll(config.args)
        }
        def buildArgsOption = buildArgs.collect{ k, v -> "${k}='${v}'"}.join(" --build-arg ")
        def dockerfile = config.dockerfile ? config.dockerfile : "Dockerfile"
        stage("Login ${config.registry}") {
            withCredentials([usernamePassword(credentialsId: config.registryAuth, passwordVariable: 'registryPass', usernameVariable: 'registryUser')]) {
                sh "docker login ${config.registry} -u ${env.registryUser} -p ${env.registryPass}"
            }
        }
        stage("Build ${config.name} image") {
            sh "docker build  -t ${config.registry}/${config.img_subpath}/${config.name}:${tag} --build-arg ${buildArgsOption} -f ${dockerfile} ."
        }
        stage("Push ${config.name} image") {
                // for (v in [env.GIT_SHA, 'latest', tag]) {
                for (v in [tag, 'latest']) {
                    sh "docker tag ${config.registry}/${config.img_subpath}/${config.name}:${tag} ${config.registry}/${config.img_subpath}/${config.name}:${v}"
                    sh "docker push ${config.registry}/${config.img_subpath}/${config.name}:${v}"
		}

            return tag
        }
    //}
}
